/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package registry;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import shared.ServerInfo;

/**
 *
 * @author eric
 */
public class RegistryRefresher implements Runnable {

    boolean keepRefreshing;
    private final Map<InetAddress, ServerInfo> servers;
    PicRegistryController controller;

    RegistryRefresher(PicRegistryController controller) {
        servers = new HashMap<InetAddress, ServerInfo>();
        this.controller = controller;

    }

    public void updatedList(Map<InetAddress,ServerInfo> newMap)
    {
        synchronized(servers)
        {
            servers.putAll(newMap);
        }
        synchronized(this)
        {
            notify();
        }
    }

    public void run() {
        keepRefreshing = true;
        while (keepRefreshing) {
            List<InetAddress> removeList = new ArrayList();
            if (servers.size() > 0)
            {
                for(InetAddress address : servers.keySet())
                {
                    Socket socket=null;
                    try {
                        socket = new Socket(address, servers.get(address).getPort());
                    } catch (IOException ex) {
                        removeList.add(address);
                    }
                    if (socket!=null)
                        try {
                        socket.close();
                    } catch (IOException ex) {

                    }
                }
            }
            servers.clear();
            controller.removeServers(removeList);

            synchronized (this) {
                try {
                    wait();
                } catch (InterruptedException ex) {
                    keepRefreshing = false;
                }
            }

        }
    }
}
